<template>
  <a-spin :spinning="confirmLoading">
    <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol">
      <a-row>
    <a-col :span="24">
        <a-form-item label="医院" v-bind="validateInfos.hospitalid">
            <a-select
              v-model:value="formData.hospitalid"
              placeholder="请选择医院"
              :disabled="disabled"
              :options="hospitalOptions"
              :field-names="{ label: 'label', value: 'value' }"
              show-search
              :filter-option="filterHospitalOption"
              @change="handleHospitalChange"
            />
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="医院名字" v-bind="validateInfos.hospitalname">
                <a-input v-model:value="formData.hospitalname" placeholder="选择医院后自动填充"
                         :disabled="true"></a-input>
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="项目组ID" v-bind="validateInfos.projectid">
            <a-tree-select
              v-model:value="formData.projectid"
              :tree-data="projectTreeData"
              :field-names="{ label: 'title', value: 'value', children: 'children' }"
              :disabled="!formData.hospitalid || disabled"
              :placeholder="formData.hospitalid ? '请选择项目组' : '请先选择医院'"
              show-search
              tree-node-filter-prop="title"
              @change="handleProjectChange"
            />
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="项目组名字" v-bind="validateInfos.projectname">
                <a-input v-model:value="formData.projectname" placeholder="选择项目组后自动填充"
                         :disabled="true"></a-input>
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="标题" v-bind="validateInfos.title">
                <a-input v-model:value="formData.title" placeholder="请输入标题"
                         :disabled="disabled"></a-input>
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="内容" v-bind="validateInfos.contain">
                <j-editor v-model:value="formData.contain"
                          :disabled="disabled"/>
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="价格" v-bind="validateInfos.price">
                <a-input-number v-model:value="formData.price" placeholder="请输入价格"
                                style="width: 100%" :disabled="disabled"/>
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="图片地址" v-bind="validateInfos.pic">
                <j-image-upload
                  :fileMax="1"
                  v-model:value="formData.pic"
                  :disabled="disabled"
                ></j-image-upload>
        </a-form-item>
    </a-col>
    <a-col :span="24">
        <a-form-item label="视频地址" v-bind="validateInfos.video">
                <j-upload
                  :maxCount="1"
                  v-model:value="formData.video"
                  :disabled="disabled"
                ></j-upload>
        </a-form-item>
    </a-col>
      </a-row>
    </a-form>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
    import JEditor from '/@/components/Form/src/jeecg/components/JEditor.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, getDepartName, queryAllTreeListByPid } from '../NewsShop.api';
  import { Form } from 'ant-design-vue';
  
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: ()=>{} },
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
            hospitalid: '',
            hospitalname: '',
            projectid: '',
            projectname: '',
            title: '',
            contain: '',
            price: undefined,
            pic: '',
            video: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  const projectTreeData = ref<any[]>([]);
  const hospitalOptions = ref<any[]>([]);
  
  //表单验证
  const validatorRules = {
  };
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 医院选项搜索过滤
  function filterHospitalOption(input, option) {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  }

  // 加载医院选项
  async function loadHospitalOptions() {
    try {
      const result = await defHttp.get({
        url: '/nurse_hospital/nurseHospital/rootList',
        params: {
          pageNo: 1,
          pageSize: 9999,
        },
      });
      if (result && result.records && Array.isArray(result.records)) {
        hospitalOptions.value = result.records.map((item) => ({
          value: item.id,
          label: item.name,
          text: item.name,
          sysOrgCode: item.sysOrgCode,
        }));
      }
    } catch (error) {
      console.error('加载医院选项失败:', error);
    }
  }

  // 医院选择改变事件
  async function handleHospitalChange(value) {
    console.log('医院选择改变，value:', value);
    const hospital = hospitalOptions.value.find((item) => item.value === value);
    if (hospital) {
      formData.hospitalname = hospital.text || hospital.label;
      console.log('设置医院名称:', formData.hospitalname);
    }
    console.log('当前formData.hospitalid:', formData.hospitalid);
    console.log('当前formData.hospitalname:', formData.hospitalname);

    // 清空项目组
    formData.projectid = '';
    formData.projectname = '';
    projectTreeData.value = [];

    // 加载项目组数据
    if (value && hospital && hospital.sysOrgCode) {
      try {
        const departResult = await getDepartName({ orgCode: hospital.sysOrgCode });
        
        if (departResult && departResult.id) {
          const treeResult = await queryAllTreeListByPid({ pid: departResult.id });
          
          if (treeResult && Array.isArray(treeResult)) {
            projectTreeData.value = convertToTreeData(treeResult);
          }
        }
      } catch (error) {
        console.error('加载项目组数据失败:', error);
      }
    }
  }

  // 转换部门数据为树形选择器格式
  function convertToTreeData(data) {
    if (!Array.isArray(data)) return [];

    return data.map((item) => {
      const nodeId = item.id || item.key || item.value;
      const nodeTitle = item.departName || item.name || item.title || item.label;

      return {
        title: nodeTitle,
        key: nodeId,
        value: nodeId,
        children: item.children && item.children.length > 0 ? convertToTreeData(item.children) : undefined,
      };
    });
  }

  // 项目组选择改变事件
  function handleProjectChange(value, label, extra) {
    console.log('项目组选择改变，value:', value);
    console.log('项目组选择改变，label:', label);
    
    const findNode = (nodes, targetKey) => {
      for (const node of nodes) {
        if (node.key === targetKey) return node;
        if (node.children && node.children.length > 0) {
          const found = findNode(node.children, targetKey);
          if (found) return found;
        }
      }
      return null;
    };

    const selectedNode = findNode(projectTreeData.value, value);
    if (selectedNode) {
      formData.projectname = selectedNode.title;
    } else if (Array.isArray(label) && label.length > 0) {
      formData.projectname = label[label.length - 1];
    } else if (typeof label === 'string') {
      formData.projectname = label;
    }
    
    console.log('当前formData.projectid:', formData.projectid);
    console.log('当前formData.projectname:', formData.projectname);
  }

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  async function add() {
    await loadHospitalOptions();
    await edit({});
  }

  /**
   * 编辑
   */
  async function edit(record) {
    console.log('编辑record:', record);
    // 先加载医院选项
    await loadHospitalOptions();
    
    await nextTick(async () => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
      
      console.log('编辑后的formData:', formData);
      console.log('hospitalid:', formData.hospitalid);
      console.log('hospitalname:', formData.hospitalname);
      console.log('projectid:', formData.projectid);
      console.log('projectname:', formData.projectname);

      // 如果有医院ID，加载项目组数据
      if (formData.hospitalid) {
        await nextTick();
        
        const hospital = hospitalOptions.value.find((item) => item.value === formData.hospitalid);
        
        if (hospital && hospital.sysOrgCode) {
          try {
            const departResult = await getDepartName({ orgCode: hospital.sysOrgCode });
            
            if (departResult && departResult.id) {
              const treeResult = await queryAllTreeListByPid({ pid: departResult.id });
              
              if (treeResult && Array.isArray(treeResult)) {
                projectTreeData.value = convertToTreeData(treeResult);
              }
            }
          } catch (error) {
            console.error('编辑时加载项目组数据失败:', error);
          }
        }
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    // 触发表单验证
    await validate();
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化 - 创建副本避免直接修改响应式对象
    let model = { ...formData };
    
    if (model.id) {
      isUpdate.value = true;
    }
    
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    
    console.log('提交的数据:', model);
    
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    height: 500px !important;
    overflow-y: auto;
    padding: 14px;
  }
</style>
